import React, { useState, useEffect } from 'react';
import { LeftOutline } from 'antd-mobile-icons';
import { useNavigate } from 'react-router-dom';
import { api } from '../../../utils/request';
import './training.css'
// 使用public目录中的图片
const image = '/image/nv1.jpg';

// 数据类型定义
interface TrainingRecord {
  id: number;
  title: string;
  category: string;
  price: string;
  level: string;
  duration: string;
  durationRange: string;
  equipment: string;
  img: string;
  created_at: string;
}

interface MyTraining {
  id: number;
  title: string;
  level: string;
  equipments: string;
  parts: string;
  warmup: number;
  stretch: number;
  createdAt: number;
  img: string;
}


const Trainings: React.FC = () => {
  const navigate = useNavigate();
  
  // 状态：当前激活的标签页（训练记录、我的预定）
  const [activeTab, setActiveTab] = useState<'records' | 'reservations'>('records');
  
  // 数据状态
  const [trainingRecords, setTrainingRecords] = useState<TrainingRecord[]>([]);
  const [myReservations, setMyReservations] = useState<MyTraining[]>([]);
  const [loading, setLoading] = useState(true);

  // 从数据库获取训练记录
  const fetchTrainingRecords = async () => {
    try {
      const response = await api.get('http://localhost:5000/api/training/trainings');
      if (response.ok) {
        const data = await response.json();
        setTrainingRecords(data);
        console.log('训练记录数据:', data);
      } else {
        console.error('获取训练记录失败:', response.status);
      }
    } catch (error) {
      console.error('获取训练记录失败:', error);
    }
  };

  // 从数据库获取我的预定
  const fetchMyReservations = async () => {
    try {
      const response = await api.get('http://localhost:5000/api/training/mytrainings');
      if (response.ok) {
        const data = await response.json();
        setMyReservations(data);
        console.log('我的预定数据:', data);
      } else {
        console.error('获取我的预定失败:', response.status);
      }
    } catch (error) {
      console.error('获取我的预定失败:', error);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      await Promise.all([
        fetchTrainingRecords(),
        fetchMyReservations()
      ]);
      setLoading(false);
    };
    
    loadData();
  }, []);

  // 渲染训练记录列表
  const renderRecords = () => {
    if (loading) {
      return (
        <div className="loading-container">
          <div className="loading-text">加载中...</div>
        </div>
      );
    }

    if (trainingRecords.length === 0) {
      return (
        <div className="empty-container">
          <div className="empty-text">暂无训练记录</div>
        </div>
      );
    }

    // 按日期分组训练记录
    const groupedRecords = trainingRecords.reduce((groups, record) => {
      const date = new Date(record.created_at).toISOString().split('T')[0];
      if (!groups[date]) {
        groups[date] = [];
      }
      groups[date].push(record);
      return groups;
    }, {} as Record<string, TrainingRecord[]>);

    return (
      <div className="records-container">
        {Object.entries(groupedRecords).map(([date, records]) => (
          <div key={date} className="record-date-group">
            <div className="date-header">
              <span>{date}</span>
              <span>{records.length}项训练, {records.reduce((total, record) => {
                const duration = parseInt(record.duration) || 0;
                return total + duration;
              }, 0)}分钟</span>
            </div>
            {records.map((record) => (
              <div key={record.id} className="record-item">
                <img
                  src={record.img || image}
                  alt={record.title}
                  className="record-image"
                />
                <div className="record-info">
                  <div className="record-title">{record.title}</div>
                  <div className="record-time">{record.duration} - {record.level}</div>
                </div>
                <div className="record-status">✔️</div>
              </div>
            ))}
          </div>
        ))}
      </div>
    );
  };

  // 渲染我的预定列表
  const renderReservations = () => {
    if (loading) {
      return (
        <div className="loading-container">
          <div className="loading-text">加载中...</div>
        </div>
      );
    }

    if (myReservations.length === 0) {
      return (
        <div className="empty-container">
          <div className="empty-text">暂无预定记录</div>
        </div>
      );
    }

    return (
      <div className="reservations-container">
        {myReservations.map((reservation) => (
          <div key={reservation.id} className="reservation-item">
            <img
              src={reservation.img || image}
              alt={reservation.title}
              className="item-img"
            />
            <div className="item-title">{reservation.title}</div>
            <div className="item-detail">难度：{reservation.level}</div>
            <div className="item-detail">部位：{reservation.parts}</div>
            <div className="item-detail">设备：{reservation.equipments}</div>
          </div>
        ))}
      </div>
    );
  };


  return (
    <div className="trainings-container">
      {/* 顶部导航栏 */}
      <div className="header">
        <div className="back-btn" onClick={() => navigate('/index/profile')}>
          <LeftOutline />
        </div>
        <div className="page-title">我的训练</div>
        <div className="save-btn"></div>
      </div>

      {/* 标签栏 */}
      <div className="tabs-container">
        <button
          onClick={() => setActiveTab('records')}
          className={`tab-button ${activeTab === 'records' ? 'active' : ''}`}
        >
          训练记录
        </button>
        <button
          onClick={() => setActiveTab('reservations')}
          className={`tab-button ${activeTab === 'reservations' ? 'active' : ''}`}
        >
          我的预定
        </button>
      </div>

      {/* 内容区：根据激活标签渲染对应内容 */}
      {activeTab === 'records' && renderRecords()}
      {activeTab === 'reservations' && renderReservations()}
    </div>
  );
};

export default Trainings;
